<script setup lang="ts">
import Page from '@/components/Page.vue';
import { http } from '@/services/http';
import type { ResponseData, Comment, CommentPageData, recomment } from '@/types';
import { API_ROOT, RATE_OPTIONS } from '@/types/constant';
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, reactive, ref, watch } from 'vue';
import CommentDialog from './CommentDialog.vue';
import { useRoute, useRouter } from 'vue-router';
import RecommentDialog from './RecommentDialog.vue';
import GetRecomment from './GetRecomment.vue';
import { useUserStore } from '@/stores/user';
import { getBookImageUrl } from '@/utils';

const commentForm = reactive<Comment>({
  reviewer: 0,
  imgList: '',
  hasRecommented: false,
  id: 0,
  order_id: 0,
  book_name: '',
  transaction_date: '',
  rate: 0,
  content: '',
  fileList: [],
  book_img: '',
});

const pageData = reactive({
  myComment: 0,
  rate: '',
  currentPage: 1,
  pageSize: 15,
  total: 60,
  queryString: '',
});

const commentList = ref<Comment[]>([]);
const dialogVisible = ref<boolean>(false);
const dialogRecommentVisible = ref<boolean>(false);
const bigImgList = ref<string[]>([]);
const highlightedRow = ref<number | null>(null);

const route = useRoute();
const router = useRouter();

const getCommentListByPage = () => {
  http.post<ResponseData<CommentPageData>>('/comment/page', pageData).then((res) => {
    commentList.value = res.data.list;
    console.log(11, commentList.value);

    pageData.total = res.data.total;
  });
};

const highlightCommentRow = () => {
  const id = Number(route.params.commentId);
  if (id) {
    const row = commentList.value.find((comment) => comment.order_id === id);
    if (row) {
      highlightedRow.value = row.order_id;
    } else {
      highlightedRow.value = null; // 没有找到匹配行时设置为 null
    }
  } else {
    highlightedRow.value = null; // 没有 id 时设置为 null
  }
};
const handleCurrentChange = (u: number) => {
  pageData.currentPage = u;
  getCommentListByPage();
};

const handleDelete = (id: number) => {
  ElMessageBox.confirm('此操作将永久删除该评论, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      http.get<ResponseData>('/comment/del', { id: id }).then((ResponseData) => {
        ElMessage({ type: 'success', message: ResponseData.msg });
        getCommentListByPage();
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      });
    });
};

const getCommentId = (comment_id: number) => {
  if (comment_id) {
    const num1 = comment_id;
    console.log(num1);

    http
      .get('/comment/hasRecommented', { num1: num1 })
      .then((response) => {
        console.log('Response:', response);
        const index = commentList.value.findIndex((item) => item.id === comment_id);
        if (index !== -1) {
          commentList.value[index].hasRecommented = true;
        }
      })
      .catch((error) => {
        console.error('Error:', error);
      });
  }
};
const recommentForm = reactive<recomment>({
  id: 0,
  order_id: 0,
  book_img: '',
  book_name: '',
  transaction_date: '',
  rate: 0,
  content: '',
  comment_time: '',
  img_list: '',
  comment_id: 0,
});
const dialogRecommentVisible1 = ref(false);
const handleReComment = (row: any, hasRecommented: boolean) => {
  if (hasRecommented) {
    http.get<ResponseData>('/comment/getrecomment', { id: row.id }).then((res) => {
      console.log(1115, res);
      recommentForm.book_name = res.data.book_name;
      recommentForm.transaction_date = res.data.transaction_date;
      recommentForm.img_list = res.data.img_list;
      recommentForm.rate = res.data.rate;
      recommentForm.content = res.data.content;
    });
    console.log(10101, recommentForm);

    dialogRecommentVisible1.value = true;
  } else {
    dialogRecommentVisible.value = true;
    commentForm.book_name = row.book_name;
    commentForm.transaction_date = row.transaction_date;
    commentForm.id = row.id;
    commentForm.book_img = row.book_img;
    commentForm.order_id = row.order_id;
    commentForm.imgList = row.img_list;
  }
};

const handleClear = (img_list: any) => {
  dialogVisible.value = true;
  bigImgList.value = img_list.split(',');
};

const dialogClosed = () => {
  dialogVisible.value = false;
  bigImgList.value = [];
};
const getNewPage = () => {
  const commentId = Number(route.params.commentId);
  pageData.queryString = commentId.toString();
  getCommentListByPage();
};

const userStore = useUserStore();
const findOwner = () => {
  pageData.myComment = userStore.userInfo.id;
  http.post<ResponseData<CommentPageData>>('/comment/MyComment', pageData).then((res) => {
    commentList.value = res.data.list;
    pageData.total = res.data.total;
    pageData.queryString = '';
    pageData.rate = '';
  });
};
const findWhoBuy = () => {
  pageData.myComment = userStore.userInfo.id;
  http.post<ResponseData<CommentPageData>>('/comment/CommentMy', pageData).then((res) => {
    commentList.value = res.data.list;
    pageData.total = res.data.total;
    pageData.queryString = '';
    pageData.rate = '';
  });
};

onMounted(() => {
  const commentId = Number(route.params.commentId);
  if (commentId) {
    getNewPage();
  }
  getCommentListByPage();
  highlightCommentRow(); // 确保在 mounted 时也调用一次
});

const getAllComment = () => {
  http.post<ResponseData<CommentPageData>>('/comment/all', pageData).then((res) => {
    commentList.value = res.data.list;
    pageData.total = res.data.total;
    pageData.queryString = '';
    pageData.rate = '';
  });
};
const tableRowClassName = ({ row, rowIndex }: { row: Comment; rowIndex: number }) => {
  if (highlightedRow.value && row.order_id === highlightedRow.value) {
    return 'highlight';
  }
  return '';
};
</script>

<template>
  <Page class="comment-view">
    <template #header>
      <div class="content-header">
        <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>评论数据</el-breadcrumb-item>
          <el-breadcrumb-item>评论</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </template>
    <div class="filter-container">
      <el-input placeholder="评论id/书名/评价内容" v-model="pageData.queryString" class="filter-item" />
      <el-select v-model="pageData.rate" placeholder="评价等级" class="filter-item">
        <el-option v-for="item in RATE_OPTIONS" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button class="custom-btn-1" @click="handleCurrentChange(1)">查询评论</el-button>
      <el-button class="custom-btn-2" @click="getAllComment()">所有评论</el-button>
      <el-button type="success" @click="findOwner()">我的评价</el-button>
      <el-button type="primary" @click="findWhoBuy()">我的商品评价</el-button>
    </div>
    <el-table
      class="tableContainer"
      size="small"
      current-row-key="id"
      :data="commentList"
      stripe
      highlight-current-row
      :row-class-name="tableRowClassName"
    >
      <el-table-column prop="id" label="评论id" width="60" />
      <el-table-column prop="book_img" label="书本图片" width="150" align="center">
        <template v-slot="scope">
          <el-image :src="getBookImageUrl(scope.row.book_img)" style="width: 60px; height: auto">
            <template #error>
              <div class="img-fallback">
                <el-icon><Notebook /></el-icon>
                <div class="img-fallback-text">Cover</div>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="book_name" label="书名" align="center" width="100px" />
      <el-table-column label="评价等级" width="250" align="center">
        <template #default="scope">
          <div class="rate-container">
            <el-rate
              v-model="scope.row.rate"
              :texts="['重开吧', '真心一般', '就那样', '有点东西', '牛杯666']"
              show-text
              disabled
            ></el-rate>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="评价内容" align="center" />
      <el-table-column prop="transaction_date" label="购买时间" align="center" />
      <el-table-column prop="comment_time" label="评论时间" align="center" />
      <el-table-column label="评价图片" width="200" align="center">
        <template v-slot="scope">
          <el-carousel
            :interval="4000"
            type="card"
            height="150px"
            @click="handleClear(scope.row.img_list)"
            v-if="scope.row.img_list && scope.row.img_list.length > 0"
          >
            <el-carousel-item v-for="(image, index) in scope.row.img_list.split(',')" :key="index">
              <img
                :src="getBookImageUrl(image.trim())"
                alt="Uploaded Image"
                style="width: 100%; height: 100%; object-fit: cover"
              />
            </el-carousel-item>
          </el-carousel>
          <div v-else>
            <p>暂无图片</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="220">
        <template #default="scope">
          <el-button
            size="small"
            :type="scope.row.hasRecommented ? 'info' : 'success'"
            @click="handleReComment(scope.row, scope.row.hasRecommented)"
            class="comment-button"
            :class="{ 'has-commented1': scope.row.hasRecommented }"
          >
            <span class="button-text">{{ scope.row.hasRecommented ? '有追评' : '追评' }}</span>
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      size="small"
      class="pagination"
      @current-change="handleCurrentChange"
      :current-page="pageData.currentPage"
      :page-size="pageData.pageSize"
      layout="total, prev, pager, next, jumper"
      :total="pageData.total"
    >
    </el-pagination>
    <comment-dialog v-model="commentForm" />
    <el-dialog title="神评图片" v-model="dialogVisible" width="80%" @close="dialogClosed" draggable overflow>
      <el-carousel :interval="4000" type="card" height="600px" v-if="bigImgList && bigImgList.length > 0">
        <el-carousel-item v-for="(image, index) in bigImgList" :key="index">
          <img
            :src="getBookImageUrl(image.trim())"
            alt="Uploaded Image"
            style="width: 100%; height: 100%; object-fit: cover"
          />
        </el-carousel-item>
      </el-carousel>
    </el-dialog>
  </Page>
  <recomment-dialog v-model="commentForm" v-model:recommentDialog="dialogRecommentVisible" @comment-id="getCommentId" />
  <get-recomment v-model="recommentForm" v-model:recommentDialog="dialogRecommentVisible1" />
</template>

<style>
.custom-btn-1 {
  background-color: #ed6464; /* 按钮背景色 */
  border-color: #6eff69; /* 边框颜色 */
  color: rgba(255, 255, 255, 0.763); /* 文字颜色 */
}

.custom-btn-2 {
  background-color: #4a90e2; /* 按钮背景色 */
  border-color: #4a90e2; /* 边框颜色 */
  color: white; /* 文字颜色 */
}
/* 高亮并闪烁的动画 */
@keyframes highlightAndFlash {
  0% {
    background-color: transparent; /* 红色背景 */
  }
  50% {
    background-color: yellow; /* 透明背景 */
  }
  100% {
    background-color: transparent; /* 保持透明背景 */
  }
}

.highlight {
  animation: highlightAndFlash 0.7s linear 3;
}

.filter-container {
  display: flex;
  margin: 16px 0;
}

.filter-item {
  width: 200px;
  margin-right: 12px;
}

.pagination {
  margin-top: 10px;
  margin-bottom: 10px;
}

.el-image {
  display: inline-flex;
}

.img-fallback {
  width: 50px;
  height: 70px;
  box-shadow: 0 0 2px #333;
  margin: 5px;
  padding: 2px 0 0 5px;
}

.img-fallback .img-fallback-text {
  font-weight: 900;
  color: #fe8738;
}
.comment-button {
  position: relative;
}

.comment-button .button-text {
  transition: opacity 0.3s;
}

.comment-button.has-commented .button-text {
  opacity: 1;
}

.comment-button.has-commented:hover .button-text {
  opacity: 0;
}

.comment-button.has-commented1:hover::after {
  color: aqua;
  content: '查看追评';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  white-space: nowrap;
}
</style>
